package com.fuhe.chen.vendingmachine.security;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * SHIRO配置类
 * 主要在这里设置过滤规则
 * 在这里指定realm对象
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean 过滤规则:对网页的访问进行权限控制
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(getDefaultWebSecurityManager());

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap();
        /*
        shiro 内置过滤规则
            anon:无需认证即可访问
            authc:通过认证可以访问
            user: 必须拥有 记住我 才能访问
            perms: 拥有对某个资源的权限才能访问
            role:拥有某个角色权限可以访问
         */
        filterChainDefinitionMap.put("/login","anon");

        filterChainDefinitionMap.put("/admin/**","roles[admin]");
        filterChainDefinitionMap.put("/admin","roles[admin]");
        filterChainDefinitionMap.put("/static/html/**","roles[admin]");

        filterChainDefinitionMap.put("/supplier/**","roles[supplier]");

        filterChainDefinitionMap.put("/app/bookOrder/*","authc");
        filterChainDefinitionMap.put("/app/userInfo/**","authc");


        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        //当用户没有权限时 自动跳转到页面
        bean.setLoginUrl("/login");
        bean.setUnauthorizedUrl("/noAuth");

        return bean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //关联userRealm
        defaultWebSecurityManager.setRealm(userRealm());
        return defaultWebSecurityManager;
    }

    //Realm, realm对象需要自定义
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    /**
     * thymeleaf整合
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
